//
//  PayViewController.m
//  ZiJinLian
//
//  Created by 🐛 on 2017/5/11.
//  Copyright © 2017年 lzy. All rights reserved.
//

#import "PayViewController.h"
#import "PayTableViewCell.h"
#import "PayResultViewController.h"
#import "ZJShopCarViewController.h"
#import "LMPopInputPasswordView.h"
#import "ZJSecuritycodeViewController.h"
#import "BurseViewController.h"
#import "VowViewController.h"
#import "DealersViewController.h"
#import "MyWishViewController.h"
#import "ShopDetailViewController.h"
#import "AllOrderViewController.h"
#import "OrderDetailViewController.h"
@interface PayViewController ()<UITableViewDelegate,UITableViewDataSource,LMPopInputPassViewDelegate>
{
    LMPopInputPasswordView *popView;
}

@property (nonatomic,strong) UITableView *tableView;
@property (nonatomic,strong) NSArray *img;
@property (nonatomic,strong) NSArray *name;
@property (nonatomic,strong) PayTableViewCell *lastCell;
@property (nonatomic,assign) NSInteger paymentType;
@end

@implementation PayViewController

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"icon_back"] style:UIBarButtonItemStyleDone target:self action:@selector(backAction)];
}
-(void)backAction{
    for (UIViewController*view in self.navigationController.viewControllers ) {
        if ([view isKindOfClass:[ShopDetailViewController class]]) {
            [self.navigationController popToViewController:view animated:YES];
        }else if ([view isKindOfClass:[VowViewController class]]){
            [self.navigationController popToViewController:view animated:YES];
        }else if ([view isKindOfClass:[DealersViewController class]]){
            [self.navigationController popToViewController:view animated:YES];
        }else if ([view isKindOfClass:[MyWishViewController class]]){
            [self.navigationController popToViewController:view animated:YES];
        }else if ([view isKindOfClass:[AllOrderViewController class]]){
            [self.navigationController popToViewController:view animated:YES];
        }else if ([view isKindOfClass:[OrderDetailViewController class]]){
            [self.navigationController popToViewController:view animated:YES];
        }else{
            //不确保其他还有遗漏 如有遗漏请手动添加以去除连续pop效果
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title=MyString(@"确认支付");
    [self.view addSubview:self.tableView];
    self.name=@[MyString(@"微信支付"),MyString(@"支付宝支付"),MyString(@"钱包支付")];
    self.img=@[@"icon_payment_wechat",@"icon_alipay",@"deal_wallet"];
    UIButton *butt=[[UIButton alloc]initWithFrame:CGRectMake(0, MainH-49-64, MainW, 49)];
    [butt setTitle:MyString(@"确认支付") forState:UIControlStateNormal];
    [butt setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    butt.titleLabel.font=[UIFont systemFontOfSize:15];
    butt.backgroundColor=Red_Color;
    [butt addTarget:self action:@selector(payClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:butt];
    // Do any additional setup after loading the view.
}
-(UITableView *)tableView{
    if (!_tableView) {
        _tableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 0, MainW, MainH-64-49) style:UITableViewStylePlain];
        _tableView.delegate=self;
        _tableView.scrollEnabled =NO;
        _tableView.dataSource=self;
        _tableView.backgroundColor=Gray_Color;
        _tableView.separatorColor=Gray_Color;
        [_tableView registerNib:[UINib nibWithNibName:@"PayTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"PayTableViewCell"];
    }
    return _tableView;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 50;
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 50;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 3;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    PayTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"PayTableViewCell"];
    cell.name.text=self.name[indexPath.row];
    cell.imag.image=[UIImage imageNamed:self.img[indexPath.row]];
    if(indexPath.row==0) {
        self.lastCell=cell;
        cell.statue.image=[UIImage imageNamed:@"icon_rb_pre"];
        self.paymentType=111;
    }
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    PayTableViewCell*cell=[tableView cellForRowAtIndexPath:indexPath];
    if (self.lastCell!=cell) {
        cell.statue.image=[UIImage imageNamed:@"icon_rb_pre"];
        self.lastCell.statue.image=[UIImage imageNamed:@"icon_rb_nor"];
        self.lastCell=cell;
    }
    if (indexPath.row==0) {
        self.paymentType=111;
    }else if (indexPath.row==1){
        self.paymentType=101;
    }else{
        self.paymentType=301;
    }
}
-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *view=[[UIView alloc]init];
    view.backgroundColor=Gray_Color;
    UIView *bottom=[[UIView alloc]initWithFrame:CGRectMake(0, 0,MainW, 40)];
    bottom.backgroundColor=[UIColor whiteColor];
    [view addSubview:bottom];
//    NSArray *Arry=@[MyString(@"产品数量"),MyString(@"产品总额"),MyString(@"优惠券抵扣"),MyString(@"应付金额")];
	NSArray *Arry=@[MyString(@"应付金额")];

//    NSArray *Array=@[[NSString stringWithFormat:@"%@",self.orderDic[@"totalNumber"]],[NSString stringWithFormat:@"%@",self.orderDic[@"totalPayment"]],@"0",[NSString stringWithFormat:@"%@",self.orderDic[@"due"]]];

	
	
	NSString *price = self.orderDic[@"due"];
	if (price.length == 0) {
		price = self.orderDic[@"finalPayment"];
	}
	NSArray *Array=@[[NSString stringWithFormat:@"¥%@",price]];

    for (int i=0; i<Array.count; i++) {
        MYLabel *label=[[MYLabel alloc]initWithFrame:CGRectMake(10, 10+30*i, MainW/2, 20)];
        label.text=Arry[i];
        label.textColor=TextColor3;
        [bottom addSubview:label];
        MYLabel *price=[[MYLabel alloc]initWithFrame:CGRectMake(MainW/2, 10+30*i, MainW/2-10, 20)];
        if (i==0) {
            price.text=[NSString stringWithFormat:@"%@",Array[i]];
        }else{
            price.text=[NSString stringWithFormat:@"¥ %@.0",Array[i]];
        }
        price.textAlignment=NSTextAlignmentRight;
        price.textColor=Red_Color;
        [bottom addSubview:price];
    }
    
    return view;
}
-(void)payClick{
    NSMutableDictionary *dic=[[NSMutableDictionary alloc]init];
//    dic[@"userId"]=[ZJUserDefaultsTools getCurrentUserID];
    dic[@"payNo"]=self.orderSn;
    dic[@"paymentType"]=@(self.paymentType);
    if (self.paymentType==301) {
        [self loadcountDetailRequest];
        return;
    }
	NSString *url = self.isNewUrl ? API_SEAT_PAY_LIST:API_OrderPAY;
	
    [self doHttpRequestWithApi:url method:GET dic:dic successBlock:^(NSDictionary *dic2) {
        if (self.paymentType==101) {
            NSString *appScheme=@"aliPay2088621752287648";
            [[AlipaySDK defaultService] payOrder:dic2[@"data"] fromScheme:appScheme callback:^(NSDictionary *resultDic) {
            }];
            [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(pushClick) name:@"Ali_PaySuccess" object:nil];
            [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(pushOrderClickbtn) name:@"Ali_PayFairl" object:nil];
        }else if (self.paymentType==111){
            //NSLog(@"支付订单 %@",dic2);
            NSData *jsonData = [dic2[@"data"] dataUsingEncoding:NSUTF8StringEncoding];
            NSError *err;
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                                options:NSJSONReadingMutableContainers error:&err];
            
            if(err) {
                //NSLog(@"json解析失败：%@",err);
            }else{
                //NSLog(@"%@",dic);
                //调起微信支付
                PayReq* req             = [[PayReq alloc] init];
                req.openID              = [dic objectForKey:@"appid"];
                req.partnerId           = [dic objectForKey:@"partnerid"];
                req.prepayId            = [dic objectForKey:@"prepayid"];
                req.nonceStr            = [dic objectForKey:@"noncestr"];
                NSMutableString *stamp  = [dic objectForKey:@"timestamp"];
                req.timeStamp           = stamp.intValue;
                req.package             = [dic objectForKey:@"package"];
                req.sign                = [dic objectForKey:@"sign"];
                
                [WXApi sendReq:req];
                // 创建通知
                [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(pushClick) name:@"WX_PaySuccess" object:nil];
                [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(pushOrderClickbtn) name:@"WX_PayFairl" object:nil];
            }

        }else{
            
        }

    }];
}
- (void)pushClick
{
    NSMutableDictionary *dic=[[NSMutableDictionary alloc]init];
    dic[@"userId"]=[ZJUserDefaultsTools getCurrentUserID];
    dic[@"orderSn"]=self.orderSn;
    //dic[@"paymentType"]=@(111);
    [self doHttpRequestWithApi:API_ConfirmPAY method:POST dic:dic successBlock:^(NSDictionary *dic) {
        
        NSLog(@"支付成功");
    }];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    PayResultViewController *vc=[[PayResultViewController alloc]init];
    vc.result=Succeed;
     vc.IsNear=self.isNear;
    [self.navigationController pushViewController:vc animated:YES];
    
}
-(void)pushOrderClickbtn{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    PayResultViewController *vc=[[PayResultViewController alloc]init];
    vc.result=Failure;
    vc.IsNear=self.isNear;
    [self.navigationController pushViewController:vc animated:YES];
    //NSLog(@"支付失败");
}
#pragma mark ---LMPopInputPassViewDelegate
-(void)buttonClickedAtIndex:(NSUInteger)index withText:(NSString *)text
{
    //NSLog(@"buttonIndex = %li password=%@",(long)index,text);
    if(index==1){
        if(text.length==0){
            //NSLog(@"密码长度不正确");
        }else if(text.length<6){
            //NSLog(@"密码长度不正确");
        }else{
            
            //NSLog(@"输出的密码:%@",text);
            [self loadApplyRequest:text];
            
            //            }
        }
    }else{
        //NSLog(@"老子忘记密码了");
    }
}
-(void)loadApplyRequest:(NSString*)password{
    [self showDialog];
    NSMutableDictionary*dic=[NSMutableDictionary dictionary];
    dic[@"payNo"]=self.orderSn;
    dic[@"paymentType"]=[NSString stringWithFormat:@"%ld",(long)self.paymentType];
    dic[@"password"]=password;
    AFHTTPSessionManager*maneger=[AFHTTPSessionManager manager];
	
	NSString *url = self.isNewUrl ? API_SEAT_PAY_LIST:Requestpayment;
    [maneger GET:[NSString stringWithFormat:@"%@%@",baseURL,url] parameters:dic progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"%@",responseObject);
        [self dismissDialog];
        if ([responseObject[@"status"] isEqualToNumber:@(0)]) {
            PayResultViewController*vc=[[PayResultViewController alloc]init];
            vc.result=Succeed;
            vc.IsNear=self.isNear;
            [self.navigationController pushViewController:vc animated:YES];
        }else if([responseObject[@"status"] isEqualToNumber:@(1)]){
            [self showToast:responseObject[@"msg"]];
        }else{
            
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self dismissDialog];
    }];
    
    
}
-(void)buttonClickedForgetpassWord{
    ZJSecuritycodeViewController*vc=[[ZJSecuritycodeViewController alloc]init];
    vc.binkCart=2;
    vc.curphoneStr=[ZJUserDefaultsTools getCurrentUserPhone];
    [self.navigationController pushViewController:vc animated:YES];
    //NSLog(@"忘记密码了");
}
-(void)deviceOrientationDidChange:(NSObject*)sender{
    UIDevice* device = [sender valueForKey:@"object"];
    if(device.orientation==UIInterfaceOrientationLandscapeLeft||device.orientation==UIInterfaceOrientationLandscapeRight)
    {
        popView.frame = CGRectMake((self.view.frame.size.width - 250)*0.5, 50, 250, 130);
    }
    else if(device.orientation==UIInterfaceOrientationPortrait||device.orientation==UIInterfaceOrientationPortraitUpsideDown)
    {
        popView.frame = CGRectMake((self.view.frame.size.width - 250)*0.5, 50, 250, 130);
    }
}
-(void)loadcountDetailRequest{
    
    NSMutableDictionary*dic=[NSMutableDictionary dictionary];
    dic[@"userId"]=[ZJUserDefaultsTools getCurrentUserID];
    [self doHttpRequestWithApi:ACCOUNTDETAIL method:GET dic:dic successBlock:^(NSDictionary *dic) {
        [self dismissDialog];
        if ([dic[@"data"][@"hasPassword"] intValue]==1) {
            popView = [[LMPopInputPasswordView alloc]init];
            popView.frame = CGRectMake((self.view.frame.size.width - 255)*0.5, 50, 255, 150);
            popView.delegate = self;
            [popView pop];
        }else if([dic[@"data"][@"hasPassword"] intValue]==0){
            LXAlertView *alert=[[LXAlertView alloc]initWithTitle:nil message:@"未设置支付密码,是否立即设置" cancelBtnTitle:@"立即设置" otherBtnTitle:nil clickIndexBlock:^(NSInteger clickIndex) {
            ZJSecuritycodeViewController*vc=[[ZJSecuritycodeViewController alloc]init];
                vc.binkCart=4;
                vc.curphoneStr=[ZJUserDefaultsTools getCurrentUserPhone];
                [self.navigationController pushViewController:vc animated:YES];
            }];
            [alert showLXAlertView];
            
//            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                [self showToast:@"您暂未开通钱包支付功能"];
//            });
            
        }
    }];
    
}

@end
